package pers.cyw.oraclejavaproject.util;

import java.sql.*;

public class JdbcTemplate {
    // 无rs返回操作模板
    public static int update(String sql,Object...params){
        int s = 0;
        try {
            PreparedStatement pst = DBConnection.getConnection().prepareStatement(sql);
            ParameterMetaData pmd = pst.getParameterMetaData();
            if(null!= params&&params.length>0&&pmd.getParameterCount() == params.length){
                for(int i =0;i<params.length;i++){
                    pst.setObject(i+1,params[i]);
                }
                s = pst.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return s;
    }
    //查询操作模板
    public static <T> T query(String sql, ResultSetHandle<T> resultSetHandle,Object...params){
        T t = null;
        try {
            PreparedStatement pst = DBConnection.getConnection().prepareStatement(sql);
            ParameterMetaData pmd = pst.getParameterMetaData();
            //            判断是否为模糊查询
            if (sql.indexOf("like") != -1){
                for(int i =0;i<params.length;i++){
                    if (params[i] instanceof String){
                        params[i] = "%"+params[i].toString()+"%";
                    }
                }
            }
            if(null!= params&&params.length>0&&pmd.getParameterCount() == params.length){
                for(int i =0;i<params.length;i++){
                    pst.setObject(i+1,params[i]);
                }
            }
            ResultSet rs = pst.executeQuery();
            t = resultSetHandle.handle(rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return t;
    }

    //    根据ResultSet生成ArrayList
//    public static List<User> createList(ResultSet rs) throws SQLException {
//        List<User> list = new ArrayList<>();
//        while (rs.next()){
//            User u = new User();
//            u.setId(rs.getInt(1));
//            u.setName(rs.getString(2));
//            u.setPassword(rs.getString(3));
//            u.setSex(rs.getString(4));
//            u.setDate(LocalDateTime.now());
//            list.add(u);
//        }
//        return list;
//    }
}
